var mongoose = require('mongoose');

var User = require('../models/user.model') //引数据模型
//zeng
exports.create = function(req,res,next){
    var user = new User(req.body);

    user.save()
    .then(data=>{
        res.json(data)
    })
    
}

exports.get = function(req,res,next){// 获取单个页面的数据
    var id = req.params.id;
	console.log(req.params.id);
    User.finById(id,function(err,result){
    	res.json(result);
    })
}

//shan 
exports.update = function(req,res,next){

    var id = req.params.id;
    //现在操作的都是mongoose 而不是mongodb 
    User.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json({msg:'数据修改成功',status:200});// 如果要返回数据，这里返回的是修改之前的数据
    })
}
//chu
exports.remove = function(req,res,next){
    var id = req.params.id;

    User.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
}
exports.list = function(req,res,next){
	
	console.log(req.body)
	
    var page = (req.body.page)?req.body.page:1;
    var limit = (req.body.limit)?req.body.limit:2;
	
    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0){
        name = req.body.name;
        queryCondition = { "name":new RegExp(name,'i')}
    }
    User.paginate(queryCondition, { page: page, limit: limit }, function(err, result) {
        //res.json(result);  
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    // result.docs
    // result.total
    // result.limit - 10
    // result.page - 3
    // result.pages
  });
}
